# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: xguo

from coin.exchange.base.kr_rest.product import NativeProduct, NormProduct
from coin.exchange.bitstamp_v2.kr_rest.constants import (
    symbol_list,
    native_currency_list,
    quote_currency_list,
)
from coin.exchange.bitstamp_v2.kr_rest.currency import BitstampCurrency


# native_symbol for query, always used as part of query URL.
def parse_native_symbol(native_symbol):
  # parse native_symbol, also called url_symbol by bitstamp
  assert len(native_symbol) == 6
  assert native_symbol in symbol_list
  return native_symbol[:3], native_symbol[3:]


# native_symbol in response json.
def parse_native_symbol2(native_symbol):
  # parse native_symbol, also called currency_pair by bitstamp
  pair = native_symbol.lower().split('/')
  assert len(pair) == 2, pair
  return pair


class BitstampProduct(NativeProduct):
  _exchange = "Bitstamp"
  NativeCurrencyType = BitstampCurrency

  def __init__(self, base, quote):
    assert base != quote, (base, quote)
    assert base.native_currency in native_currency_list, base
    assert quote.native_currency in quote_currency_list, quote
    native_symbol = "%s%s" % (base.native_currency, quote.native_currency)
    NativeProduct.__init__(self, base, quote, native_symbol)

  @classmethod
  def FromProductImpl(cls, product, current_datetime):
    assert isinstance(product, NormProduct), type(product)
    return BitstampProduct(product.base, product.quote)

  @classmethod
  def FromStrNativeProductImpl(cls, product: str, current_datetime):
    assert isinstance(product, str), product
    base = None
    quote = None
    try:
      base, quote = parse_native_symbol(product)
    except AssertionError:
      pass

    try:
      base, quote = parse_native_symbol2(product)
    except AssertionError:
      pass

    if base and quote:
      return BitstampProduct(BitstampCurrency.FromStrNativeCurrency(base),
                             BitstampCurrency.FromStrNativeCurrency(quote))
    else:
      raise ValueError('Unknown product! %s', product)
